<template lang="pug">
.ignore-work-template-preview
  Dialog(
    v-model="model"
    cancel-text="取消"
    size="large"
    :title="tileName"
    v-bind:onCancel="onCancel"
    v-bind:onClose="onClose"
    :fullscreen="true"
    :hideFooter="true"
  )
    .dww-row-img(:gutter="10")
      .dww-row-img-left
        mt-card
          .dww-row-img-left-card
            .dww-row-img-left-card-header
              mt-button(type="primary",@click="onConfirm(RegistrationStateEnum.Progress)",:disabled="modeValue != 'edit'",:loading="saveLoading") 保存
              mt-button(type="primary",@click="onConfirm(RegistrationStateEnum.Diagnosed)",:disabled="modeValue != 'edit'",:loading="saveLoading") 提交
              mt-button(type="primary",@click="onConfirm(RegistrationStateEnum.Reviewed)",:disabled="modeValue == 'edit'",v-if="props.action != 'print'",:loading="saveLoading") 审核
              mt-button(type="primary",@click="onConfirm(RegistrationStateEnum.Printed)",:disabled="modeValue == 'edit'",:loading="saveLoading") 确认打印
              mt-button(type="info",@click="onExamine(RegistrationStateEnum.Progress)",:disabled="modeValue == 'edit'",v-if="props.action != 'print'",:loading="saveLoading") 取消审核
              span(v-if="props.action != 'print'") 阴阳性:
              Select(style="width: 130px;min-width: 130px;",:options="selectOptions" v-model="select",v-if="props.action != 'print'")
              el-checkbox(v-model="criticalValueShow",v-if="props.action != 'print'")
              span(v-if="props.action != 'print'") 上报危急值 
            .dww-row-img-left-card-body
              editor(ref="foEditor",v-if="foEditorShow")
      .dww-row-img-right(v-if="modeValue == 'edit'")
        mt-card
          mt-tabs(v-model="activeName")
            mt-tab-pane(name="图像采集",label="图像采集" ,labelIcon="Menu")     
              acquisition(ref="conclusionRef",:selectItemTag="selectItemTag",@imageChange="imageChange")
            mt-tab-pane(name="科室术语",label="科室术语" ,labelIcon="Menu")
              terminology(ref="terminologyRef",:selectItemTag="selectItemTag",@valueChange="valueChange",@valueAdd="valueAdd")
            mt-tab-pane(name="历史检查",label="历史检查" ,labelIcon="Menu")
              historyConclusion(ref="historyConclusionRef",:selectItemTag="selectItemTag")
  criticalValue(v-model="criticalValueShow",:selectItem="selectItemTag")
    
</template>

<script setup lang="ts">

import {
  useNotify, editor, Select, Dialog, ElMessageBox
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { useApi, type ApiBasedOptions } from "@scmt/core-api";
import { type RegistrationConclusionEntity } from "@scmt/api-pacs-registration-conclusion";
import { RegistrationStateEnum } from "@scmt/api-pacs-registration";
import { useUtils } from "@scmt/lib-utils";

import historyConclusion from "../../pacsViewer/components/historyConclusion.vue";
import terminology from "./terminology.vue";
import acquisition from "./acquisition.vue";
import criticalValue from "../../pacsViewer/components/critical-value.vue";
import { useUser } from "@scmt/common-store";
import { ExecutionStatus, PatientType } from "@scmt/api-common";
const $utils = useUtils();

const user = useUser();
const foEditor = ref<InstanceType<typeof editor>>();
//添加 Props属性
const props = defineProps({
  selectRows: Object,
  action: String,
});
//定义事件
const emit = defineEmits(['handleQuery']);

const $notify = useNotify();
const $api = useApi();

const selectItemTag = ref({});
const activeName = ref("图像采集");
const foEditorShow = ref(false);
//select选择
const select = ref(0);
const selectOptions = reactive<ApiBasedOptions>([
  { label: "阴性", value: 0 },
  { label: "阳性", value: 1 },
]);

const saveLoading = computed(() => {
  return loadingMap.saveConclusion || loadingMap.updateRegistrationState || loadingMap.updateExecutionStatus || loadingMap.saveWorkFlow;
});
//是否显示上传危急值弹框
const criticalValueShow = ref(false);

const { request, data, loadingMap } = useRequest({
  templateByEquipmentId: async (equipmentId: string) => {
    return await $api.bdm.template.queryTemplateByEquipmentId(equipmentId);
  },
  //根据登记Id查询诊断意见
  registrationConclusion: async (registrationId: string) => {
    return await $api.pacs.registrationConclusion.queryRegistrationConclusionByRegistrationId(registrationId);
  },
  //根据登记Id查询影像图片
  registrationImageData: async (registrationId: string) => {
    return await $api.pacs.imageData.queryByRegistrationId(registrationId);
  },

  //保存诊断意见
  saveConclusion: (entity: RegistrationConclusionEntity) => {
    return $api.pacs.registrationConclusion.save(entity);
  },
  //更新登记单状态
  updateRegistrationState: (item: any) => {

    return $api.pacs.registration.updateRegistrationState(item).then(() => {
      switch (item.registrationState) {
        case RegistrationStateEnum.Progress:
          $notify.success("保存成功");
          //解锁结论
          request("unlockConclusion", item.ids)
          break;
        case RegistrationStateEnum.Diagnosed:
          $notify.success("提交成功");
          //解锁结论
          request("unlockConclusion", item.ids)
          break;
        case RegistrationStateEnum.Reviewed:
          $notify.success("审核成功");
          break;
        case RegistrationStateEnum.Printed:
          $notify.success("确认打印成功");
          break;
        default:
          break;
      }
      emit("handleQuery", {});
      //保存成功关闭弹框
      model.value = false;

    });
  },
  //更新住院医嘱执行单状态
  updateExecutionStatus: (params: any) => {
    return $api.medical.medicalOrderExecution.updateExecutionStatus(params);
  },
  //保存工作流程
  saveWorkFlow: (entity: any) => {
    return $api.pacs.registrationWorkflow.save(entity);
  },
  //pacs 结论加锁
  lockConclusion: async (registrationId: string) => {
    return await $api.pacs.registrationConclusion.lockConclusion(registrationId);
  },
  //pacs 结论解锁
  unlockConclusion: async (registrationId: string) => {
    return await $api.pacs.registrationConclusion.unlockConclusion(registrationId);
  },
});

const editingObj = ref<null | RegistrationConclusionEntity>(null);
const jsonValue = ref("");
const modeValue = ref("");

const model = defineModel({
  default: false,
});
//弹框标题
const tileName = ref("查看报告");

//诊断意见
const diagnosticOpinion = ref("");
//影像所见
const imageFindings = ref("");
//弹框点击确认事件
const onConfirm = (state: string) => {
  let json = foEditor.value?.getJson();

  quaryData(JSON.parse(json), "diagnosticOpinion", diagnosticOpinion)
  quaryData(JSON.parse(json), "imageFindings", imageFindings)
  if (props.selectRows && (imageFindings.value || diagnosticOpinion.value) && editingObj.value) {
    let diagnosticOpinionValue = editingObj.value.diagnosticOpinion;
    let imageFindingsValue = editingObj.value.imageFindings;
    //判断是否修改了结论
    if (imageFindingsValue != imageFindings.value || diagnosticOpinionValue != diagnosticOpinion.value) {
      ElMessageBox.confirm("监测到检查结论已修改，您是否确认修改执行医生！", {
        title: "提示",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm" && instance) {
            if (editingObj.value) {
              editingObj.value.handleDoctorId = user.userId;
              editingObj.value.handleDoctorName = user.username;
              editingObj.value.reportDoctorId = user.userId;
              editingObj.value.reportDoctorName = user.username;

            }
            done();
            saveConclusion(imageFindings.value, diagnosticOpinion.value, state);
          } else {
            done();
            saveConclusion(imageFindings.value, diagnosticOpinion.value, state);
          }
        },
      });
    }
    else {
      saveConclusion(imageFindings.value, diagnosticOpinion.value, state);
    }


  }
  else {
    $notify.error("请添加结论!!");
  }
};
//结论表数据保存以及状态更新
const saveConclusion = (imageFindingsValue: string, diagnosticOpinionValue: string, state: string) => {
  //结论表数据保存
  if (editingObj.value && props.selectRows && props.selectRows[0]) {
    editingObj.value.imageFindings = imageFindingsValue; // 影像所见
    editingObj.value.diagnosticOpinion = diagnosticOpinionValue; // 诊断意见
    editingObj.value.isHandle = "1";
    editingObj.value.registrationId = props.selectRows[0].id;
    if (editingObj.value.checkTime && editingObj.value.checkTime.trim().length == 0) {
      editingObj.value.checkTime = $utils.getCurrentTimeString();
    }
    if (props.action == "examine") {
      editingObj.value.auditDoctorId = user.userId;
      editingObj.value.auditDoctorName = user.username;
    }
  }

  //查看报告之前为
  if ("report" == props.action) {
    //@ts-ignore
    request("saveConclusion", editingObj.value).then((res) => {
      if (res) {
        //登记单状态修改
        modificationRegistrationState(state);
      }

    });
  }
  else {
    //登记单状态修改
    modificationRegistrationState(state);
  }
}
/**
 * 登记单状态修改
 */
const modificationRegistrationState = (state: string) => {
  if (props.selectRows && props.selectRows[0] && props.selectRows[0].registrationState) {

    let registrationState = ref("");
    let ids = ref("");
    let item = { registrationState: registrationState.value, ids: ids.value, positive: "" }
    let executionStatus = 0;
    let operateContent = "";
    registrationState.value = state;
    switch (props.action) {
      case "report":
        item.positive = select.value + "";
        //影像所见 诊断意见 都有证明诊断完了
        if (imageFindings.value && diagnosticOpinion.value) {
          executionStatus = ExecutionStatus.IN_PROGRESS;
          operateContent = "出具报告";
        }
        else {
          //诊断中
          executionStatus = ExecutionStatus.IN_PROGRESS;
          operateContent = "暂存报告";
        }
        break;
      case "examine":
        item.positive = "";
        registrationState.value = RegistrationStateEnum.Reviewed;
        executionStatus = ExecutionStatus.COMPLETED;
        operateContent = "审核通过";
        break;
      case "print":
        item.positive = "";
        registrationState.value = RegistrationStateEnum.Printed;
        executionStatus = ExecutionStatus.REPORT_READY;
        operateContent = "打印报告";
        break;
      default:
        break;
    }
    let specimenIdData: any[] = [];
    props.selectRows.forEach((element: any) => {
      if (ids.value != "") {
        ids.value += ",";
      }
      ids.value += element.id;
      specimenIdData.push(element.sourceId);
    });
    item.registrationState = registrationState.value;
    item.ids = ids.value;
    request("updateRegistrationState", item).then(() => {
      //是住院才更新住院医嘱执行单状态
      if (props.selectRows) {
        if (props.selectRows[0].patientType == PatientType.INPATIENT) {
          request("updateExecutionStatus", {
            executionNumberList: specimenIdData,
            executionId: user.userId,
            executionName: user.username,
            executionStatus: executionStatus,
          });
        }
        request("saveWorkFlow", {
          registrationId: props.selectRows[0].id,
          operatePersonId: user.userId,
          operatePersonName: user.username,
          operateContent: operateContent,
        });
      }

    });


  }

};
//关闭弹框
const onCancel = () => {
  model.value = false;
};
//审核
const onExamine = (state: string) => {
  if (props.selectRows && props.selectRows[0] && props.selectRows[0].registrationState) {
    let ids = ref("");
    props.selectRows.forEach((element: any) => {
      if (ids.value != "") {
        ids.value += ",";
      }
      ids.value += element.id;
    });
    request("updateRegistrationState", { registrationState: state, ids: ids.value });
    let operateContent = "";
    if (state == RegistrationStateEnum.Progress) {
      operateContent = "取消审核";
    }
    else if (state == RegistrationStateEnum.Printed) {
      operateContent = "审核通过";
    }
    request("saveWorkFlow", {
      registrationId: props.selectRows[0].id,
      operatePersonId: user.userId,
      operatePersonName: user.username,
      operateContent: operateContent,
    });
  }

};
//取消
const onClose = () => {
  model.value = false;
  if (modeValue.value == "edit") {
    if (props.selectRows && props.selectRows.length > 0 && props.selectRows[0]) {
      let registrationId = props.selectRows[0].id;
      //解锁结论
      request("unlockConclusion", registrationId)
    }
  }
};

/**
 * 查找模板数据
 * @param templatejson 模板json
 * @param key 查询的key
 * @param resKey  需要的返回值
 */
const quaryData = (templatejson: any, key: any, resKey: any): boolean => {
  let res = false;
  if (templatejson && key) {


    if (templatejson.content && templatejson.content.length > 0) {
      if (templatejson.attrs && key == templatejson.attrs.name) {
        resKey.value = templatejson.content[0].text
        res = true;
        return res;
      }
      for (let index = 0; index < templatejson.content.length; index++) {
        const element = templatejson.content[index];
        let resFor = quaryData(element, key, resKey);
        if (resFor) {
          res = resFor;
          break;
        }
      }
    }
  }
  return res;
};
const item = ref();
const itemInit = ref(false);
//结论改变
const valueChange = (data: any) => {
  if (data && data.imageFindings && data.diagnosticOpinion && itemInit.value) {
    item.value.imageFindings = data.imageFindings;// 影像所见
    item.value.diagnosticOpinion = data.diagnosticOpinion; // 诊断意见
    foEditor.value?.destroy();
    foEditorShow.value = false;
    nextTick(() => {
      foEditorShow.value = true;
      nextTick(() => {
        foEditor.value?.initEditor(modeValue.value, jsonValue.value ?? JSON.parse(jsonValue.value), item.value);
      });
    });
  }
};
//结论追加
const valueAdd = (data: any) => {
  if (data && data.imageFindings && data.diagnosticOpinion && itemInit.value) {
    item.value.imageFindings = item.value.imageFindings ?? "";
    item.value.diagnosticOpinion = item.value.diagnosticOpinion ?? "";
    item.value.imageFindings += data.imageFindings;// 影像所见
    item.value.diagnosticOpinion += data.diagnosticOpinion; // 诊断意见
    foEditor.value?.destroy();
    foEditorShow.value = false;
    nextTick(() => {
      foEditorShow.value = true;
      nextTick(() => {
        foEditor.value?.initEditor(modeValue.value, jsonValue.value ?? JSON.parse(jsonValue.value), item.value);
      });
    });
  }
};
//数组后两个的值变成新的数组
const getLastTwoElements = (arr: any[]) => {
  // 检查数组长度是否至少为2
  if (arr.length >= 2) {
    // 使用slice方法获取后两个元素
    return arr.slice(0, 2);
  }
  // 如果数组长度小于2，则返回空数组
  return arr;
}
//结论追加
const imageChange = () => {

  foEditorShow.value = false;
  if (props.selectRows && props.selectRows.length > 0 && props.selectRows[0]) {
    let registrationId = props.selectRows[0].id;
    request("registrationImageData", registrationId).then(() => {
      let imageData = data.registrationImageData ?? [];
      if (imageData && imageData.length > 0) {
        let dcmUrl = ref<any>([]);
        imageData.forEach((element: any) => {
          if (element && element.imageData && 1 == element.isReport) {
            dcmUrl.value.push(element.imageData)
          }
        });
        item.value.dcmImage = getLastTwoElements(dcmUrl.value);

      }

      foEditorShow.value = true;
      nextTick(() => {
        foEditor.value?.initEditor(modeValue.value, jsonValue.value ?? JSON.parse(jsonValue.value), item.value);
      });
    });
  }
  else {
    foEditorShow.value = true;
  }
};
//初始化报告
const initEditor = () => {
  if (props.selectRows && props.selectRows[0]) {
    let equipmentId = props.selectRows[0].deviceId;
    let registrationId = props.selectRows[0].id;
    if (equipmentId && registrationId) {
      //let equipmentId = "ad7d5d059a38dc90b4977143f2118975";
      request("registrationConclusion", registrationId).then(() => {
        editingObj.value = $api.pacs.registrationConclusion.$$createEntity(data.registrationConclusion ?? {});
        item.value.imageFindings = "";// 影像所见
        item.value.diagnosticOpinion = ""; // 诊断意见
        if (editingObj.value.id) {
          item.value.imageFindings = editingObj.value.imageFindings;// 影像所见
          item.value.diagnosticOpinion = editingObj.value.diagnosticOpinion; // 诊断意见
        }
        request("templateByEquipmentId", equipmentId).then(() => {
          let resData = data.templateByEquipmentId ?? {};
          let resItem = $api.bdm.template.$$createEntity(resData);
          if (resData && resItem.jsonTemplate) {
            //匹配数据
            let json = JSON.parse(resItem.jsonTemplate);
            jsonValue.value = JSON.stringify(json);
          }
          request("registrationImageData", registrationId).then(() => {
            let imageData = data.registrationImageData ?? [];
            if (imageData && imageData.length > 0) {
              let dcmUrl = ref<any>([]);
              imageData.forEach((element: any) => {
                if (element && element.imageData && 1 == element.isReport) {
                  dcmUrl.value.push(element.imageData)
                }
              });
              item.value.dcmImage = getLastTwoElements(dcmUrl.value);

            }
            foEditorShow.value = true;
            item.value.doctorImage = user.info.sign;
            nextTick(() => {
              foEditor.value?.initEditor(modeValue.value, jsonValue.value ?? JSON.parse(jsonValue.value), item.value);
              itemInit.value = true;
            });
          });
        });
      });
    }
  }
};
watch(
  model,
  () => {
    if (model.value) {
      foEditor.value?.destroy();
      itemInit.value = false;
      criticalValueShow.value = false;
      foEditorShow.value = false;
      activeName.value = "图像采集";
      selectItemTag.value = {};
      nextTick(() => {
        if (props.selectRows && props.selectRows.length > 0 && props.selectRows[0]) {
          item.value = props.selectRows[0];
          let readonly = RegistrationStateEnum.Diagnosed + "," + RegistrationStateEnum.Reviewed + "," + RegistrationStateEnum.Printed;
          if (props.selectRows[0] && props.selectRows[0].registrationState && readonly.indexOf(props.selectRows[0].registrationState) > -1) {
            modeValue.value = "readonly";
          }
          else {
            modeValue.value = "edit";
          }
          if (modeValue.value == "edit") {
            request("lockConclusion", props.selectRows[0].id).then((res) => {
              if (res && res.data && res.data.isLock != 1) {
                initEditor();
              }
              else {
                $notify.error("当前报告已锁定！！");
                model.value = false;
              }

            });
          }
          else {
            initEditor();
          }
          selectItemTag.value = props.selectRows[0];

        }
        else {
          $notify.error("请先选择设备或者先绑定模板！！");
          model.value = false;
        }
      });
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped>
.ignore-work-template-preview {

  //去除表格边框
  :deep(.fo-content-wrapper [data-fo-node=table]>table>tbody>tr>td) {
    border: 0px solid #ddd;
  }

  :deep(.mt-dialog__modal) {
    height: 100vh !important;

  }

  .dww-row-img {
    display: flex;
    height: 100%;

    &-left {
      flex: 1;

      &-card {
        display: flex;
        flex-direction: column;
        height: 100%;

        &-header {
          display: flex;
          flex-shrink: 0;
          justify-items: center;
          align-items: center;
          margin-bottom: var(--mt-margin-small);

          .el-checkbox {
            margin-left: var(--mt-margin-small);
          }

          span {
            margin: 0 var(--mt-margin-small);
          }
        }

        &-body {
          display: flex;
          flex: 1;
          overflow-y: auto;
        }
      }
    }

    &-right {
      flex-shrink: 0;
      width: 610px;
      margin-left: var(--mt-margin);
    }
  }
}
</style>